#pragma once

#include "../include/web_server.h"
#include <mongoose.h>
#include <thread>
#include <set>
#include <regex>
#include <unordered_map>
#include <vector>
#include <chrono>

struct mg_mgr;
struct mg_connection;

namespace El {
namespace WebServer {

// API路由项
struct RouteItem {
    std::string method;
    std::string uri_pattern;
    HttpHandler handler;
    std::regex uri_regex; // 正则表达式对象
};

// WebSocket路由项
struct WebSocketRouteItem {
    std::string uri_pattern;
    WebSocketEventHandler handler;
    std::regex uri_regex; // 正则表达式对象
};

class HttpServerImpl : public IHttpServer {
    DISALLOW_COPY_AND_MOVE(HttpServerImpl);

public:
    static HttpServerImpl &GetInstance();
    HttpServerImpl();
    ~HttpServerImpl() override;

    bool Start() override;
    void Stop() override;
    bool SetMountPoint(const std::string &dir) override;
    void SetSSLCert(const std::string &cert_file, const std::string &key_file) override;
    void AddBearerToken(const std::string &token) override;
    void RemoveBearerToken(const std::string &token) override;
    bool HasBearerToken(const std::string &token) override;
    void AddAuthExemptUrl(const std::string &url_pattern) override;
    void RemoveAuthExemptUrl(const std::string &url_pattern) override;
    bool RegisterHandler(const std::string &method, const std::string &uri_pattern, HttpHandler handler) override;
    
    // 新WebSocket接口
    bool RegisterWebSocketHandler(const std::string &uri_pattern, WebSocketEventHandler handler);
    bool SendWebSocketTextMessage(void* connection, const std::string &message);
    bool SendWebSocketBinaryMessage(void* connection, const std::vector<uint8_t> &data);
    void CloseWebSocketConnection(void* connection, int status_code, const std::string& reason);
    bool GetWebSocketConnectionInfo(void* connection, WebSocketConnectionInfo& info);
    std::vector<void*> GetAllWebSocketConnections(const std::string& uri_pattern = "");
    int BroadcastWebSocketMessage(const std::string& uri_pattern, const std::string &message);

private:
    static void HandleHttpEvent(struct mg_connection *c, int ev, void *ev_data, void *fn_data);
    void HandleHttpRequest(struct mg_connection *c, int ev, void *ev_data);
    bool MatchRoute(const std::string &method, const std::string &uri, RouteItem *route);
    bool FindWebSocketRoute(const std::string &uri, WebSocketRouteItem *route);
    bool ValidateToken(const std::string &token);
    bool IsAuthExempt(const std::string &uri);
    bool ValidateAuthHeader(const mg_str *auth_header);
    void HandleWebSocketEvent(struct mg_connection *c, int ev, void *ev_data);

private:
    // 默认证书路径
    std::string cert_file_;
    std::string key_file_;

    // 鉴权相关
    std::set<std::string> bearer_tokens_;      // Bearer tokens集合
    std::vector<std::regex> auth_exempt_urls_; // 免鉴权URL列表

    mg_mgr *mgr_ = nullptr;
    bool running_ = false;
    std::string root_dir_;                      // 网页根目录
    std::vector<RouteItem> routes_;             // 添加路由表
    std::vector<WebSocketRouteItem> ws_routes_; // WebSocket路由表
    std::thread serverThread_;
    
    // WebSocket连接到URI的映射
    std::unordered_map<mg_connection*, std::string> ws_connection_uris_;
    
    // WebSocket连接信息缓存
    std::unordered_map<mg_connection*, WebSocketConnectionInfo> ws_connection_infos_;
};

} // namespace WebServer
} // namespace El